<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Location;
use app\common\library\Socket;
use app\common\model\Ground as GroundModel;
use app\common\model\GroundType;
use app\common\model\Device;
use app\common\model\GroundChild;
use addons\recharge\model\MoneyLog;
use app\common\model\DeviceOrder;
use fast\Http;
use think\Db;

/**
 * 示例接口
 */
class Ground extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test', 'test1','getGroundList'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->socket = new Socket();
    }

    /**
     * 场地引流命令
     * @return void
     */
    public function ylGround()
    {
        $id = $this->request->post('id');
        $yl_timed = $this->request->post('yl_timed');
        $yl_time_end = $this->request->post('yl_time_end');
        $yl_djjg = $this->request->post('yl_djjg');
        $yl_cpp = $this->request->post('yl_cpp');
        $type = $this->request->post('type');
        if (!$id || !$yl_timed || !$yl_time_end || !$yl_djjg || !$yl_cpp) {
            $this->error('参数错误');
        }
//        $ground = GroundModel::get($id);
//        if(!$ground){
//            $this->error('场地不存在');
//        }
//        //查询场地下所有设备
//        $devices = Device::where('ground_id',$ground->id)->select();
        if ($type == 1) {//场地
            $ground = GroundModel::get($id);
            if (!$ground) {
                $this->error('场地不存在');
            }
            //查询场地下所有设备
            $devices = Device::where('ground_id', $ground->id)->select();
        } else {
            //查询场地下所有设备
            $devices = Device::where('id', $id)->select();
        }
        Db::startTrans();
        try {
            foreach ($devices as $v) {
                $device = Device::get($v->id);
                if ($device) {
                    $device->save(['yl_timed' => $yl_timed, 'yl_time_end' => $yl_time_end, 'yl_djjg' => $yl_djjg, 'yl_cpp' => $yl_cpp]);
                    $this->socket->awaitBeckon($device->name, $yl_timed . '~' . $yl_time_end, $yl_djjg, $yl_cpp);
                }

            }
            if ($type == 1) {
                $ground->save(['yl_timed' => $yl_timed, 'yl_time_end' => $yl_time_end, 'yl_djjg' => $yl_djjg, 'yl_cpp' => $yl_cpp]);
            }

            Db::commit();

        } catch (\Exception $e) {
            Db::rollback();
            $this->error('设置失败');
        }
        $this->success('设置成功');
    }

    /**
     * 出泡泡命令
     * @return void
     */
    public function cpp()
    {
        $id = $this->request->post('id');
        $cpp = $this->request->post('cpp');
        $type = $this->request->post('type');
        if (!$id || !$cpp || !$type) {
            $this->error('参数错误');
        }

        if ($type == 1) {//场地
            $ground = GroundModel::get($id);
            if (!$ground) {
                $this->error('场地不存在');
            }
            //查询场地下所有设备
            $devices = Device::where('ground_id', $ground->id)->select();
        } else {
            //查询场地下所有设备
            $devices = Device::where('id', $id)->select();
        }

        Db::startTrans();
        try {
            $arr = [];
            foreach ($devices as $v) {
                $device = Device::get($v->id);
                if ($device) {
                    $device->save(['cpp' => $cpp]);
                    $arr[] = ['device_name' => $device->name, 'type' => 1, 'time' => $cpp];
                }
            }
            if ($arr) {
                $this->socket->startDev($arr);
            }
            if ($type == 1) {
                $ground->save(['cpp' => $cpp]);
            }

            Db::commit();

        } catch (\Exception $e) {
            Db::rollback();
            $this->error('设置失败' . $e->getLine());
        }
        $this->success('设置成功');
    }

    /**
     * 音量命令
     * @return void
     */
    public function yl()
    {
        $id = $this->request->post('id');
        $yinliang = $this->request->post('yinliang');
        $type = $this->request->post('type', 1);
        if (!$id || !$yinliang || !$type) {
            $this->error('参数错误');
        }

        if ($type == 1) {//场地
            $ground = GroundModel::get($id);
            if (!$ground) {
                $this->error('场地不存在');
            }
            //查询场地下所有设备
            $devices = Device::where('ground_id', $ground->id)->select();
        } else {
            //查询场地下所有设备
            $devices = Device::where('id', $id)->select();
        }

        Db::startTrans();
        try {
            foreach ($devices as $v) {
                $device = Device::get($v->id);
                if ($device) {
                    $device->save(['yinliang' => $yinliang]);
                    $this->socket->volDev($device->name, $yinliang);
                }
            }
            if ($type == 1) {
                $ground->save(['yinliang' => $yinliang]);
            }

            Db::commit();

        } catch (\Exception $e) {
            Db::rollback();
            $this->error('设置失败');
        }
        $this->success('设置成功');
    }

    /**
     * 音量命令
     * @return void
     */
    public function dg()
    {
        $id = $this->request->post('id');
        $dg_start = $this->request->post('dg_start');
        $dg_end = $this->request->post('dg_end');
        $type = $this->request->post('type', 1);
        if (!$id || !$dg_start || !$dg_end || !$type) {
            $this->error('参数错误');
        }

        if ($type == 1) {//场地
            $ground = GroundModel::get($id);
            if (!$ground) {
                $this->error('场地不存在');
            }
            //查询场地下所有设备
            $devices = Device::where('ground_id', $ground->id)->select();
        } else {
            //查询场地下所有设备
            $devices = Device::where('id', $id)->select();
        }

        Db::startTrans();
        try {
            foreach ($devices as $v) {
                $device = Device::get($v->id);
                if ($device) {
                    $device->save(['dg_start' => $dg_start, 'dg_end' => $dg_end]);
                    $this->socket->ledTime($device->name, $dg_start . '~' . $dg_end);
                }
            }
            if ($type == 1) {
                $ground->save(['dg_start' => $dg_start, 'dg_end' => $dg_end]);
            }

            Db::commit();

        } catch (\Exception $e) {
            Db::rollback();
            $this->error('设置失败');
        }
        $this->success('设置成功');
    }

    /**
     * 灯开关命令
     * @return void
     */
    public function kg()
    {
        $id = $this->request->post('id');
        $led_kg = $this->request->post('led_kg');
        $dj_kg = $this->request->post('dj_kg');
        $music_kg = $this->request->post('music_kg');
        $type = $this->request->post('type', 1);
        if (!$id) {
            $this->error('参数错误');
        }

        if ($type == 1) {//场地
            $ground = GroundModel::get($id);
            if (!$ground) {
                $this->error('场地不存在');
            }
            //查询场地下所有设备
            $devices = Device::where('ground_id', $ground->id)->select();
        } else {
            //查询场地下所有设备
            $devices = Device::where('id', $id)->select();
        }

        Db::startTrans();
        try {
            foreach ($devices as $v) {
                $device = Device::get($v->id);
                if ($device) {
                    if ($led_kg || $led_kg == 0) {
                        $device->save(['led_kg' => $led_kg]);
                        $this->socket->ledDev($device->name, $led_kg);
                    }
                    if ($dj_kg || $dj_kg == 0) {
                        $device->save(['dj_kg' => $dj_kg]);
                        $this->socket->stopDev($device->name, $dj_kg);
                    }
                    if ($music_kg || $music_kg == 0) {
                        $device->save(['music_kg' => $music_kg]);
                        $this->socket->musicDev($device->name, $music_kg);
                    }
                }
            }
            if ($type == 1) {
                if ($led_kg || $led_kg == 0) {
                    $ground->save(['led_kg' => $led_kg]);
                }
                if ($dj_kg || $dj_kg == 0) {
                    $ground->save(['dj_kg' => $dj_kg]);
                }
                if ($music_kg || $music_kg == 0) {
                    $ground->save(['music_kg' => $music_kg]);
                }

            }

            Db::commit();

        } catch (\Exception $e) {
            Db::rollback();
            $this->error('设置失败');
        }
        $this->success('设置成功');
    }


    /**
     * 更新所有场所的经纬度
     * @return void
     */
    public function updateLocation()
    {

        // 获取所有场所
        $grounds = GroundModel::select();
        // 解析所有场所的地址
        foreach ($grounds as $ground) {
            $location = Location::addressToLocation($ground->city . $ground->address);
            $ground->save(['lat' => $location['lat'], 'lng' => $location['lng']]);
        }
        $this->success('更新成功');
    }

    /**
     * 场地列表 地图展示
     * @return void
     */
    public function listForMap()
    {
        $keywords = $this->request->post('keywords');
        $lng = $this->request->post('lng');
        $lat = $this->request->post('lat');
        $type = $this->request->post('type');
        $yj_status = $this->request->post('yj_status');


        //查询所有场地
        $list = GroundModel::where('status','normal')->order('id desc')
            ->select();

        $all_ground_ids = array_column($list, 'id');

        // 获取所有绑定设备
        $device_list = Device::where('ground_id', 'in', $all_ground_ids)->select();
        $total_devices = count($device_list);

        // 获取所有代理
        $child_list = GroundChild::with('user')->where('user.type', '=', '2')->select();

        $grouped_childs = [];
        foreach ($child_list as $child) {
            $grouped_childs[$child->ground_id][] = $child;
        }

        //设备根据场地分组
        $grouped_devices = [];
        foreach ($device_list as $device) {
            $grouped_devices[$device->ground_id][] = $device;
        }


        $total_health_devices = 0;
        // 组装数据
        foreach ($list as &$ground) {
            $ground_id = $ground->id;

            $ground->total_devices = 0;
            $ground->health_devices = 0;

            $ground->yj_status = 0;

            $yj_status1_count = 0;
            $yj_status2_count = 0;
            $online_count = 0;
            $offline_count = 0;
            $water_warning_count = 0;
            $ele_warning_count = 0;
            if (isset($grouped_devices[$ground_id])) {
                $ground_devices = $grouped_devices[$ground_id];
                $ground->total_devices = count($ground_devices);

                foreach ($ground_devices as $device) {
                    if ($device->yj_status == 0) {
                        $total_health_devices++;
                        $ground->health_devices++;
                    } elseif ($device->yj_status == 1) {
                        $yj_status1_count++;
                    } elseif ($device->yj_status == 2) {
                        $yj_status2_count++;
                    }

                    if ($device->type == 'online') {
                        $online_count++;
                    } elseif ($device->type == 'offline') {
                        $offline_count++;
                    } elseif ($device->type == 'water_warning') {
                        $water_warning_count++;
                    } elseif ($device->type == 'ele_warning') {
                        $ele_warning_count++;
                    }
                }

                if ($offline_count > 0) {
                    $ground->device_type = 'offline';
                }else {
                    $ground->device_type = 'online';
                }

                if ($yj_status1_count > 0 && $yj_status2_count > 0) {
                    $ground->yj_status = 3;
                } elseif ($yj_status1_count > 0) {
                    $ground->yj_status = 1;
                } elseif ($yj_status2_count > 0) {
                    $ground->yj_status = 2;
                }

            }

            if (isset($grouped_childs[$ground_id])) {
                if (!empty($grouped_childs[$ground_id][0]->user->mobile)) {
                    $ground['child_mobile'] = $grouped_childs[$ground_id][0]->user->mobile;
                }
            }

            // 计算距离
            if ($lng && $lat) {
                $ground->distance = Location::calculateDistance($ground->lat, $ground->lng, $lat, $lng);
            }
        }


        // 过滤
        $list = array_filter($list, function ($ground) use ($yj_status, $type, $keywords) {
            $type_falg = empty($type) || $ground->type == $type;
            $yj_status_flag= true;
            if(isset($yj_status)) {
                if($yj_status == 3) {
                    $yj_status_flag = $ground->yj_status != 0;
                }else {
                    $yj_status_flag = $ground->yj_status == (int)$yj_status;
                }
            }
            $keywords_flag= empty($keywords) || strpos($ground->name, $keywords) !== false;
            return $type_falg && $yj_status_flag && $keywords_flag;
        });

        // 对列表进行排序，根据距离从小到大排序
        usort($list, function ($a, $b) {
            if (!isset($a->distance) || !isset($b->distance)) {
                return 0;
            }
            return $a->distance <=> $b->distance;
        });


        $this->success('获取成功', [
            'total_devices' => $total_devices,
            'total_health_devices' => $total_health_devices,
            'list' => $list
        ]);
    }

    /**
     * 通过经纬度获取场地
     * @return void
     */
    public function getGroundList()
    {
        $lng = $this->request->post('lng');
        $lat = $this->request->post('lat');
        $keywords = $this->request->post('keywords');
        $where = [];
        if ($keywords) {
            $where['name'] = ['like', '%' . $keywords . '%'];
        }
        $subquery = "(6371 * acos(  
            cos(radians($lat)) *   
            cos(radians(lat)) *   
            cos(radians(lng) - radians($lng)) +   
            sin(radians($lat)) *   
            sin(radians(lat))  
          ))";
        $list = GroundModel::where('status', 'normal')
            ->where($where)
            ->field("*,$subquery as distance")
            ->order('distance asc')
            ->order('id desc')->select();
        foreach ($list as &$ground){
            $ground->distance = round($ground->distance, 2);
        }
        $this->success('获取成功', $list);
    }

    public function all()
    {
        $list = GroundModel::with('type')->order('id desc')->select();
        $this->success('获取成功', $list);

    }

    /**
     * 场地列表
     * @return void
     */
    public function list()
    {
        $where = [];
//        $where['ground.user_id'] = $this->auth->id;
        //查询此商家所有场地
        $user_group = GroundModel::where('user_id', $this->auth->id)->column('id');
        //查询此商家所有场地
        $ground_ids = GroundChild::where('user_id', $this->auth->id)->column('ground_id');
        if (!$ground_ids) {
            $ground_ids = [-1];
        }

        $where['ground.id'] = ['in', array_merge($ground_ids, $user_group)];
        $keywords = $this->request->post('keywords');
        if (!empty($keywords)) {
            $where['ground.name'] = ['like', '%' . $keywords . '%'];
        }
//        $list = GroundModel::with('type')->where($where)->paginate()->each(function ($item){
//            //下级代理
//            $item['child'] = GroundChild::alias('gc')
//                ->field('u.nickname')
//                ->join('user u','u.id=gc.user_id','left')
//                ->where('gc.ground_id',$item['id'])
//                ->select();
//            //设备数量
//            $item['device_all'] = Device::where('ground_id',$item['id'])->count();
//            $item['device_online'] = Device::where('ground_id',$item['id'])->where('type','online')->count();
//            $item['device_offline'] = Device::where('ground_id',$item['id'])->where('status','offline')->count();
//            //查询订单数量
//            $item['order_num'] = DeviceOrder::where('ground_id',$item['id'])->where('status','paid')->count();
//            //查询收益
//            $item['shouyi'] = MoneyLog::where('event_id',$item['id'])->where('user_id',$this->auth->id)->sum('money');
//            $item['createtime'] = date('Y-m-d H:i:s',$item['createtime']);
//            return $item;
//        });
        $list = GroundModel::with('type')->where($where)->order('id desc')->select();
        foreach ($list as &$item) {
            //下级代理
            $item['child'] = GroundChild::alias('gc')
                ->field('u.nickname')
                ->join('user u', 'u.id=gc.user_id', 'left')
                ->where('gc.ground_id', $item['id'])
                ->select();
            //设备数量
            $item['device_all'] = Device::where('ground_id', $item['id'])->count();
            $item['device_online'] = Device::where('ground_id', $item['id'])->where('type', 'online')->count();
            $item['device_offline'] = Device::where('ground_id', $item['id'])->where('type', 'offline')->count();
            //查询订单数量
            $item['order_num'] = DeviceOrder::where('ground_id', $item['id'])->where('is_gifts', 0)->where('status', 'paid')->count();
            //查询收益
            $item['shouyi'] = MoneyLog::where('event_id', $item['id'])->where('user_id', $this->auth->id)->sum('money');
            $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
        }
        $this->success('获取成功', $list);
    }

    //场地详情
    public function getGroundDetails()
    {
        $id = $this->request->post('id');
        $info = GroundModel::get($id);
        if ($info) {
            $info->child = GroundChild::alias('gc')
                ->field('u.id,u.nickname,u.mobile,gc.divide_rate')
                ->join('user u', 'u.id=gc.user_id', 'left')
                ->where('gc.ground_id', $info->id)
                ->select();
            $this->success('获取成功', $info);
        } else {
            $this->error('获取失败');
        }
    }

    /**
     * 添加/修改场地
     * @return void
     */
    public function editGround()
    {
        $data = $this->request->post();
        if (empty($data['id'])) {
            $ground = new GroundModel();
        } else {
            $ground = GroundModel::get($data['id']);
        }
        $child = isset($data['child']) ? $data['child'] : [];
        if ($child) {
            // 提取所有age值
            $divide_rate = array_column($child, 'divide_rate');
            // 计算总和
            $sum = array_sum($divide_rate);
            if ($sum > 100) {
                $this->error('下级分润比例不能超过100%');
            }
        }
        unset($data['child']);
        $data['user_id'] = $this->auth->id;
        $data['updatetime'] = time();
        $res = $ground->save($data);
        if ($res) {
            if (!empty($child)) {
                foreach ($child as $v) {
                    $v['ground_id'] = $ground->id;
                    $is_exist = GroundChild::where('ground_id', $v['ground_id'])->where('user_id', $v['user_id'])->find();
                    if ($is_exist) {
                        $v['updatetime'] = time();
                        GroundChild::where('ground_id', $v['ground_id'])->where('user_id', $v['user_id'])->update($v);
                    } else {
                        $v['createtime'] = time();
                        GroundChild::create($v);
                    }
                }
            }
            $this->success('保存成功');
        } else {
            $this->error('保存失败');
        }
    }


    /**
     * 添加/修改场地
     * @return void
     */
    public function editGroundChild()
    {
        $data = $this->request->post();
        if (empty($data['id'])) {
            $ground = new GroundModel();
        } else {
            $ground = GroundModel::get($data['id']);
        }
        $child = isset($data['child']) ? $data['child'] : [];
        if ($child) {
            // 提取所有age值
            $divide_rate = array_column($child, 'divide_rate');
            // 计算总和
            $sum = array_sum($divide_rate);
            if ($sum > 100) {
                $this->error('下级分润比例不能超过100%');
            }
        }
        unset($data['child']);
        $data['user_id'] = $this->auth->id;
        $data['updatetime'] = time();
        $res = $ground->save($data);
        if ($res) {
            GroundChild::where('ground_id', $ground->id)->delete();
            if (!empty($child)) {
                foreach ($child as $v) {
                    $v['ground_id'] = $ground->id;
                    $is_exist = GroundChild::where('ground_id', $v['ground_id'])->where('user_id', $v['user_id'])->find();
                    if ($is_exist) {
                        $v['updatetime'] = time();
                        GroundChild::where('ground_id', $v['ground_id'])->where('user_id', $v['user_id'])->update($v);
                    } else {
                        $v['createtime'] = time();
                        GroundChild::create($v);
                    }
                }
            }
            $this->success('保存成功');
        } else {
            $this->error('保存失败');
        }
    }


    /**
     * 获取场地类型
     * @return void
     */
    public function getType()
    {
        $list = GroundType::all();
        $this->success('获取成功', $list);
    }

    /**
     * 绑定设备
     * @author li688
     * @date 2024/8/6  下午2:52
     * @notes
     */
    public function bindDevice()
    {
        $name = $this->request->post('name');
        $ground_id = $this->request->post('ground_id');
        if (!$ground_id) {
            $this->error('请选择场地');
        }
        $ground = GroundModel::get($ground_id);
        if (!$ground) {
            $this->error('场地不存在');
        }
        if ($ground['user_id'] != $this->auth->id) {
            $this->error('您没有权限');
        }
        $info = Device::where('name', $name)->find();
        if ($info) {
            if ($info['user_id']) {
                $this->error('设备已被绑定');
            }
            $update = [];
            $update['user_id'] = $this->auth->id;
            $update['ground_id'] = $ground_id;
            $res = Device::where('name', $name)->update($update);
            if ($res) {
                $this->success('绑定成功');
            } else {
                $this->error('绑定失败');
            }
        } else {
            $this->error('设备不存在');
        }
    }

    /**
     * 设备列表
     * @return void
     */
    public function deviceList()
    {
        $where = [];
        $keywords = $this->request->post('keywords');
        if (!empty($keywords)) {
            $where['device.name'] = ['like', '%' . $keywords . '%'];
        }
        $type = $this->request->post('type');
        if (!empty($type)) {
            $where['device.type'] = $type;
        }
        $yj_status = $this->request->post('yj_status');
        if ($yj_status || $yj_status === '0') {
            $where['device.yj_status'] = $yj_status;
        }
        $ground_id = $this->request->post('ground_id');
        $whereor = [];
        $ground_ids = [];
        if ($this->auth->type != 0) {
            if ($ground_id) {
                $where['device.ground_id'] = $ground_id;
            } else {
                $user_group = GroundModel::where('user_id', $this->auth->id)->column('id');
                //查询此商家所有场地
                $ground_ids = GroundChild::where('user_id', $this->auth->id)->column('ground_id');
                if (!$ground_ids) {
                    $ground_ids = [-1];
                }
                $where['device.ground_id'] = ['in', array_merge($ground_ids, $user_group)];
//                $whereor['device.user_id'] = $this->auth->id;
//                dump($whereor);exit;
//                $where['device.ground_id'] = ['<>',0];
            }

        } else {

            if (!empty($ground_id)) {
                $where['device.ground_id'] = $ground_id;
            }
            $where['device.user_id'] = $this->auth->id;
        }

        $status = $this->request->post('status');
        if (!empty($status)) {
            $where['device.status'] = $status;
        }
//        $list = Device::with('ground')->where($where)->paginate()->each(function ($item){
//            //下级代理
//            $item['child'] = GroundChild::alias('gc')
//                ->field('u.nickname')
//                ->join('user u','u.id=gc.user_id','left')
//                ->where('gc.ground_id',$item['ground_id'])
//                ->select();
//            //查询订单数量
//            $item['order_num'] = DeviceOrder::where('device_id',$item['id'])->where('status','paid')->count();
//            //查询收益
//            $item['shouyi'] = MoneyLog::where('device_id',$item['id'])->where('user_id',$this->auth->id)->sum('money');
//            return $item;
//        });
        $list = Device::with('ground')->where($where)
            ->order('id desc')->select();
//        echo count($list);exit;
//        echo Device::getLastSql();exit;
        foreach ($list as &$item) {
            //下级代理
            $item['child'] = GroundChild::alias('gc')
                ->field('u.nickname')
                ->join('user u', 'u.id=gc.user_id', 'left')
                ->where('gc.ground_id', $item['ground_id'])
                ->select();
            //查询订单数量
            $item['order_num'] = DeviceOrder::where('device_id', $item['id'])->where('ground_id', $item['ground_id'])->where('is_gifts', 0)->where('status', 'paid')->count();
            //查询收益
            $item['shouyi'] = MoneyLog::where('device_id', $item['id'])->where('user_id', $this->auth->id)->sum('money');
        }
        $this->success('获取成功', $list);
    }


    /**
     * 添加/修改场地
     * @return void
     */
    public function editDevice()
    {
        $id = $this->request->post('id');
        $type = $this->request->post('type');
        $status = $this->request->post('status');
        $Device = Device::get($id);
        if ($type) {
            $Device->type = $type;
        }
        if ($status) {
            $Device->status = $status;
        }
        $Device->updatetime = time();
        if ($Device->save()) {
            $this->success('保存成功');
        } else {
            $this->error('保存失败');
        }
    }

    /**
     * 删除设备
     * @return void
     */
    public function delDevice()
    {
        $id = $this->request->post('id');

        $Device = Device::get($id);

//       $Device->deletetime = time();
        $Device->user_id = 0;
        $Device->ground_id = 0;
        $Device->updatetime = time();
        if ($Device->save()) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 删除场地
     * @return void
     */
    public function delGround()
    {
        $id = $this->request->post('id');

        $Device = GroundModel::get($id);
        //查询场地下是否有设备
        $device = Device::where('ground_id', $id)->find();
        if ($device) {
            $this->error('场地下有设备，无法删除');
        }

        $Device->deletetime = time();
        $Device->updatetime = time();
        if ($Device->save()) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

}
